package com.example.communitysystem.service;

import com.example.communitysystem.dto.PaginationDTO;
import com.example.communitysystem.dto.QuestionDTO;
import com.example.communitysystem.exception.CustomizeErrorCode;
import com.example.communitysystem.exception.CustomizeException;
import com.example.communitysystem.mapper.QuestionMapper;
import com.example.communitysystem.mapper.UserMapper;
import com.example.communitysystem.model.Question;
import com.example.communitysystem.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionService {

    private QuestionMapper questionMapper;

    private UserMapper userMapper;

    //传入page,size
    //实现分页功能
    //page代表第几页，size代表分页数量
    //获取传入page页的size个问题信息
    public PaginationDTO getQuestionDTOList(Integer page, Integer size) {
        //获取到所有数据量
        Integer totalCount = questionMapper.getTotalCount();
        Integer totalPage = 0;
        //计算当前的分页数量,也就是计算最大页数
        if(totalCount % size == 0){
            totalPage = totalCount/size;
        }else{
            totalPage = totalCount/size+1;
        }
        //分页类，包含分页信息
        PaginationDTO paginationDTO = new PaginationDTO();

        //判断page是否小于1，page不能小于1
        if(page < 1){
            page = 1;
        }
        //判断page是否大于最大页数，page不能大于最大页数
        if(page > totalPage){
            page = totalPage;
        }
        //存放分页信息到对象中
        paginationDTO.setPage(page);
        paginationDTO.setTotalPage(totalPage);
        //计算分页信息
        paginationDTO.setPagination(totalPage,page);

        //计算从第几条数据开始分页
        Integer offset = size*(page-1);
        //查询所有的问题信息
        List<Question> questions = questionMapper.getQuestionList(offset,size);
        List<QuestionDTO> questionDTOList = new ArrayList<>();

        for(Question question : questions){
            User user = userMapper.findById(question.getCreatorId());
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question,questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        //把分页的数据集合添加到分页的对象
        paginationDTO.setDataDTOList(questionDTOList);

        return paginationDTO;
    }

    //获取指定id用户的问题信息集合
    public PaginationDTO list(Long userId, Integer page, Integer size) {
        //获取到所有问题数据的数量
        Integer totalCount = questionMapper.getTotalCountByUserId(userId);
        Integer totalPage = 0;
        //计算当前的分页数量,也就是计算最大页数
        if(totalCount % size == 0){
            totalPage = totalCount/size;
        }else{
            totalPage = totalCount/size+1;
        }
        //分页类，包含分页信息
        PaginationDTO paginationDTO = new PaginationDTO();

        //判断page是否小于1，page不能小于1
        if(page < 1){
            page = 1;
        }
        //判断page是否大于最大页数，page不能大于最大页数
        if(page > totalPage){
            page = totalPage;
        }
        //存放分页信息到对象中
        paginationDTO.setPage(page);
        paginationDTO.setTotalPage(totalPage);
        //计算分页信息
        paginationDTO.setPagination(totalPage,page);

        //计算从第几条数据开始分页
        Integer offset = size*(page-1);
        //查询当前用户所有的问题信息
        List<Question> questions = questionMapper.getQuestionListByUserId(userId,offset,size);
        List<QuestionDTO> questionDTOList = new ArrayList<>();

        for(Question question : questions){
            User user = userMapper.findById(question.getCreatorId());
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question,questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        //把分页的数据集合添加到分页的对象
        paginationDTO.setDataDTOList(questionDTOList);

        return paginationDTO;
    }

    @Autowired
    public void setQuestionMapper(QuestionMapper questionMapper) {
        this.questionMapper = questionMapper;
    }
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //获取指定id的问题信息
    public QuestionDTO getQuestionById(Long id) {
        Question question = questionMapper.getQuestionById(id);
        //查找的问题不存在，抛出自定义异常
        if(question == null){
            throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
        }
        User user = userMapper.findById(question.getCreatorId());

        QuestionDTO questionDTO = new QuestionDTO();
        BeanUtils.copyProperties(question,questionDTO);
        questionDTO.setUser(user);

        return questionDTO;
    }

    //添加或更新信息
    public void createOrUpdate(Question question) {
        if(question.getId() == null){
            //问题不存在，则创建问题信息
            questionMapper.createQuestion(question);
        }else{
            //更新已存在的问题信息
            int updated = questionMapper.updateQuestion(question);
            //更新问题失败，抛出自定义异常信息
            if(updated != 1){
                throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
            }
        }
    }

    //增加指定问题id的问题阅读数量
    public void addReadCount(Long id) {
        //问题信息
        Question updateQuestion = new Question();
        updateQuestion.setId(id);
        updateQuestion.setReadCount(1);
        questionMapper.updateQuestionReadCount(updateQuestion.getId(), updateQuestion.getReadCount());
    }

    //通过传入的问题信息，获得相关问题信息
    public List<QuestionDTO> getRelatedQuestionDTOList(QuestionDTO questionDTO) {
        if(questionDTO == null){
            return new ArrayList<>();
        }
        String[] tags = StringUtils.split(questionDTO.getTag(),",");
        String regexpTag = Arrays.stream(tags).collect(Collectors.joining("|"));
        Question question = new Question();
        question.setId(questionDTO.getId());
        question.setTag(regexpTag);

        //获得相关问题信息
        List<Question> questionList = questionMapper.getRelatedQuestionList(question);

        List<QuestionDTO> questionDTOList = questionList.stream().map(q ->{
            QuestionDTO questionDTO1 = new QuestionDTO();
            BeanUtils.copyProperties(q,questionDTO1);

            return questionDTO1;
        }).collect(Collectors.toList());

        return questionDTOList;
    }
}
